<?php

/**
 * Base project form.
 * 
 * @package    wildlive
 * @subpackage form
 * @author     Your name here 
 * @version    SVN: $Id: BaseForm.class.php 20147 2009-07-13 11:46:57Z FabianLange $
 */
class BaseForm extends sfFormSymfony
{

  public function configure ()
  {
  
  }

  public static function formValusIsBlank ($value)
  {
    if (is_array($value))
    {
      foreach ($value as $subvalue)
      {
        if (! self::formValusIsBlank($subvalue))
          return false;
      }
      return true;
    }
    else
    {
      return $value ? false : true;
    }
  }

  /**
   * Checks if all given fields are blank
   * 
   * Used to detect empty forms that were added dynamically
   * 
   * @param array $fieldNames
   * @param array $values
   * @return boolean
   */
  protected static function __formValuesAreBlank (array $fieldNames, $values)
  {
    foreach ($fieldNames as $fieldName)
    {
      if (isset($values[$fieldName]) && ! self::formValusIsBlank($values[$fieldName]))
        return false;
    }
    return true;
  }

  public static function collectErrors (sfForm $form)
  {
    $errors = array();
    return self::__collectErrors($form, $errors);
  }

  protected static function __collectErrors (sfForm $form, array $errors)
  {
    $global_errors = $form->getGlobalErrors();
    foreach ($global_errors as $error)
    {
      $errors[] = $error;
    }
    foreach ($form as $widget)
    {
      if ($widget instanceof sfFormField && $widget->hasError())
      {
        $errors[] = $widget->getError();
      }
      elseif ($widget instanceof sfForm)
      {
        $errors = self::__collectErrors($widget, $errors);
      }
    }
    return $errors;
  }

  protected function adjustErrorMessageRequired ($field_name)
  {
    $this->validatorSchema[$field_name]->setMessage('required', sprintf('%s ist ein Pflichtfeld.', $this->widgetSchema[$field_name]->getLabel()));
  }

  protected function adjustErrroMessageInvalid ($field_name)
  {
    $this->validatorSchema[$field_name]->setMessage('invalid', sprintf('%s ist ein ungültig.', $this->widgetSchema[$field_name]->getLabel()));
  }

  public function unembedForm ($name)
  {
    if (isset($this->embeddedForms[$name]))
    {
      $form = $this->embeddedForms[$name];
      unset($this->embeddedForms[$name]);
      return $form;
    }
    else
    {
      return false;
    }
  }
}
